import React, { memo } from 'react';
import { Checkbox, Avatar, Typography } from 'antd';

interface Application {
  id: string;
  name: string;
  url: string;
  type: string;
  description: string;
}

const { Text } = Typography;

interface AppItemProps {
  app: Application;
  selectedAppIds: string[];
  onClick: () => void;
  isEditMode: boolean;
  onCheck: (id: string, isChecked: boolean) => void;
}

const AppItem: React.FC<AppItemProps> = memo(
  ({ app, onClick, isEditMode, onCheck, selectedAppIds }) => {
    const getNextValidChar = (str: string, index: number): string | undefined => {
      if (!str || typeof str !== 'string' || index >= str.length) {
        return undefined;
      }
      const char = str[index];
      // 包含中文字符的正则表达式
      const isChineseOrLetter = /^[\u4e00-\u9fa5a-zA-Z]+$/;
      if (isChineseOrLetter.test(char)) {
        return char;
      }
      return getNextValidChar(str, index + 1);
    };

    return (
      <div
        key={app?.id}
        className={`cursor-pointer rounded-lg bg-white p-2 shadow-sm transition-shadow hover:shadow-md`}
        style={{
          height: '82px',
          position: 'relative',
        }}
        onClick={onClick}
      >
        {isEditMode && (
          <Checkbox
            style={{ position: 'absolute', top: '5px', right: '5px' }}
            checked={selectedAppIds.includes(app?.id)}
            onClick={(e) => {
              e.stopPropagation();
            }}
            onChange={(e) => {
              onCheck(app?.id, e.target.checked);
            }}
          />
        )}
        <div className="flex items-start">
          <div
            className="bg-indigo-100 flex h-12 w-12 items-center justify-center rounded-lg"
            style={{
              width: '20%',
              maxWidth: '50px',
              minWidth: '30px',
            }}
          >
            <Avatar className="ml-auto h-10 w-10" style={{ backgroundColor: 'var(--brand-color)' }}>
              {getNextValidChar(app.name, 0)}
            </Avatar>
          </div>
          <div className="flex-1" style={{ width: '80%', paddingLeft: '10px' }}>
            <Text ellipsis={true} className="app-name mb-1 font-medium text-gray-900">
              {app.name}
            </Text>
            <p className="app-description line-clamp-2 text-sm text-gray-700">{app.description}</p>
          </div>
        </div>
      </div>
    );
  },
);

export default AppItem;